<?php

namespace Biz\pockets\export;

use Doraemon\amqp\ExportDataQueue;
use Doraemon\tools\Log;

class ExportData
{
    /**
     * @param callable $callback
     * @param $params
     * @return mixed
     */
    public static function addTask($callback, $params = [])
    {
        $commendParam = json_encode([
            'params' => $params,
            'callback' => $callback
        ]);
        $commendParam = base64_encode($commendParam);
        $groupId = 'be-schedulerx-api';
        $parameters['group_id'] = $groupId;
        $parameters['name'] = 'export-data';
        $parameters['command'] = '["php","/data/wwwroot/g_biz/cli/RunData/RunExportData.php","' . $commendParam . '"]';
        $res = \Hhz\Scheduler\Job::createJob($parameters);
        $res = json_decode($res, true);
        Log::info('create job result', $res);
        if ($res['statusCode'] == 200 && $res['body']['Code'] == 200) {
            $jobId = $res['body']['Data']['JobId'];
            if (!$jobId) {
                throw new \Exception('创建任务失败');
            }
            sleep(3);
            // 启动任务
            $resp = \Hhz\Scheduler\Job::executeJob($groupId, $jobId);
            $resp = json_decode($resp, true);
            $resp['JobId'] = $jobId;
            Log::info('execute job result', $resp);
            if ($resp['statusCode'] == 200 && $resp['body']['Code'] == 200) {
            } else {
                throw new \Exception('任务执行失败');
            }
        } else {
            throw new \Exception('创建任务失败');
        }
        return true;
    }

    /**
     * @param $args
     */
    public static function runTask($args)
    {
        try {
            $callback = isset($args['callback']) ? $args['callback'] : '';
            $params = isset($args['params']) ? $args['params'] : [];
            Log::debug(json_encode($callback));
            Log::debug(json_encode($params));
            if (is_callable($callback)) {
                call_user_func_array($callback, $params);
            }
        } catch (\Exception $e) {
            $trace = [
                'file' => $e->getFile(),
                'line' => $e->getLine(),
                'msg' => $e->getMessage(),
            ];
            Log::error(compact('trace', 'args'));
        }
    }

}